<template>
  <div
    class="circle-graph"
    @mousedown.capture="graphMousedown"
    @mouseup="graphMouseup">
    <relation-graph
      ref="relationGraph"
      class="relation-graph"
      :options="graphOptions"
      :on-node-click="onNodeClick">
      <template slot="node" slot-scope="{node}">
        <el-popover
          placement="bottom"
          width="200"
          trigger="hover"
          :open-delay="500"
          @show="getCustomerData(node.id)"
          @hide="customerData = null">
          <div v-loading="prpoverLoading" class="node-item-popover">
            <span class="can-visit--underline" @click="checkCustomerDetail(node.id)">{{ node.text }}</span>
            <span>负责人：<wx-open-data v-if="customerData" :openid="customerData.ownerUserName" /></span>
            <span>创建时间：{{ getCreateTime(customerData) }}</span>
          </div>
          <span slot="reference">{{ node.text }}</span>
        </el-popover>
      </template>
    </relation-graph>
  </div>
</template>

<script>
import { crmCustomerReadAPI } from '@/api/crm/customer'

import RelationGraph from '@/components/RelationGraph'

import { objDeepCopy } from '@/utils'

export default {
  // CircleGraph
  name: 'CircleGraph',

  components: {
    RelationGraph
  },

  props: {
    value: Object,
    id: [String, Number],
    showType: [String, Number]
  },

  data() {
    return {
      graphOptions: {
        defaultNodeBorderWidth: 0, // 默认的节点边框粗细（像素）
        defaultNodeColor: 'rgba(238, 178, 94, 1)', // 默认的节点背景颜色
        defaultLineColor: '#D8D8D8',
        defaultLineShape: 1, //  默认的线条样式
        defaultJunctionPoint: 'border'
        // 这里可以参考"Graph 图谱"中的参数进行设置
      },

      // 判断是否为拖拽
      x: '',
      y: '',

      customerData: null,
      prpoverLoading: false
    }
  },

  watch: {
    value: {
      handler(val) {
        this.$nextTick(() => {
          if (!val?.rootId) return
          this.setJsonData(objDeepCopy(val)) // 该组件内部有操作，复制避免影响外部数据
        })
      },
      immediate: true
    }
  },

  methods: {
    /**
     * @description: 鼠标按下
     * @param {*} e
     * @return {*}
     */
    graphMousedown(e) {
      this.x = e.x
      this.y = e.y
    },

    /**
     * @description: 点击其余地方取消聚焦
     * @param {*} e
     * @return {*}
     */
    graphMouseup(e) {
      if (e.x == this.x && e.y == this.y) {
        var _all_nodes = this.$refs.relationGraph.getNodes()
        var _all_links = this.$refs.relationGraph.getLines()
        _all_nodes.forEach(thisNode => {
          thisNode.opacity = 1
        })

        _all_links.forEach(thisLink => {
          thisLink.relations.forEach(item => {
            item.styleClass = null
            item.lineWidth = null
          })
        })

        this.$emit('graphMouseup')
      }
    },

    /**
     * 节点点击
     */
    onNodeClick(nodeObject, $event) {
      console.log('onNodeClick:', nodeObject)
      // this.getCustomerData(nodeObject.id)
      /**
       * @description:
       * @return {*}
       */
      this.doFilterByNode(nodeObject)
    },

    /**
     * 获取客户数据
     */
    getCustomerData(id) {
      this.prpoverLoading = true
      crmCustomerReadAPI({
        customerId: id
      })
        .then(res => {
          this.customerData = res.data
          this.prpoverLoading = false
        })
        .catch(() => {
          this.prpoverLoading = false
        })
    },

    /**
     * 筛选
     */
    doFilterByNode(nodeObject) {
      var allRelated = Array.from(new Set(nodeObject.targetFrom.concat(nodeObject.targetTo))).map(item => item.id)
      var _all_nodes = this.$refs.relationGraph.getNodes()
      var _all_links = this.$refs.relationGraph.getLines()

      console.log(_all_links, 456)

      _all_nodes.forEach(thisNode => {
        var _isHideThisLine = false
        if (!allRelated.includes(thisNode.id) && thisNode.id !== nodeObject.id) {
          _isHideThisLine = true
        }
        thisNode.opacity = _isHideThisLine ? 0.1 : 1
      })

      _all_links.forEach(thisLink => {
        if (thisLink.fromNode.id == nodeObject.id || thisLink.toNode.id == nodeObject.id) {
          thisLink.relations.forEach(item => {
            item.lineWidth = 2
            item.styleClass = 'is-not-opacity'
          })
        } else {
          thisLink.relations.forEach(item => {
            item.styleClass = 'is-opacity'
          })
        }
      })
    },

    cancelFocus() {
      var _all_nodes = this.$refs.relationGraph.getNodes()
      var _all_links = this.$refs.relationGraph.getLines()
      _all_nodes.forEach(thisNode => {
        thisNode.opacity = 1
      })

      _all_links.forEach(thisLink => {
        thisLink.relations.forEach(item => {
          item.styleClass = null
          item.lineWidth = null
        })
      })
    },

    /**
     * 类型筛选
     */
    doFilterByRelation(relation) {
      // const centerNode = _all_nodes.find(item => {
      //   return item.id == this.id
      // })
      // var allRelated = Array.from(new Set(centerNode.targetFrom.concat(centerNode.targetTo))).map(item => item.id)
      var _all_nodes = this.$refs.relationGraph.getNodes()
      var _all_links = this.$refs.relationGraph.getLines()

      console.log(_all_nodes, _all_links, 456)

      const nodes = []

      _all_links.forEach(thisLink => {
        if (thisLink.fromNode.id == this.id || thisLink.toNode.id == this.id) {
          thisLink.relations.forEach(item => {
            const types = {
              1: [1, 2],
              2: [3, 4]
            }[this.showType]

            if ((item.data?.relationsId == relation) ||
            ((!relation || relation === 'all') && types && types.includes(item.data?.type))) {
              // 如果 relation 没选值或者是all, showType 生效。否则 仅  relation 生效
              item.lineWidth = 2
              item.styleClass = 'is-not-opacity'
              nodes.push(thisLink.fromNode.id)
              nodes.push(thisLink.toNode.id)
            } else {
              item.styleClass = 'is-opacity'
            }
          })
        } else {
          thisLink.relations.forEach(item => {
            item.styleClass = 'is-opacity'
          })
        }
      })

      _all_nodes.forEach(thisNode => {
        var _isHideThisLine = false
        if (!nodes.includes(thisNode.id) && thisNode.id != this.id) {
          _isHideThisLine = true
        }
        thisNode.opacity = _isHideThisLine ? 0.1 : 1
      })

      // _all_links.forEach(thisLink => {
      //   if (thisLink.fromNode.id == nodeObject.id || thisLink.toNode.id == nodeObject.id) {
      //     thisLink.relations.forEach(item => {
      //       item.lineWidth = 2
      //       item.styleClass = 'is-not-opacity'
      //     })
      //   } else {
      //     thisLink.relations.forEach(item => {
      //       item.styleClass = 'is-opacity'
      //     })
      //   }
      // })
    },

    /**
     * 层级筛选
     */
    doFilterByHierarch() {
      var _all_nodes = this.$refs.relationGraph.getNodes()
      var _all_links = this.$refs.relationGraph.getLines()
      const nodes = []
      const centerNode = _all_nodes.find(item => {
        return item.id == this.id
      })
      var allRelated = Array.from(new Set(centerNode.targetFrom.concat(centerNode.targetTo))).map(item => item.id)

      _all_nodes.forEach(thisNode => {
        var _isHideThisLine = false
        if (!allRelated.includes(thisNode.id) && thisNode.id !== this.id) {
          _isHideThisLine = true
        } else {
          nodes.push(thisNode.id)
        }
        thisNode.opacity = _isHideThisLine || thisNode.opacity == 0.1 ? 0.1 : 1
      })

      _all_links.forEach(thisLink => {
        console.log(thisLink, nodes)
        if (nodes.includes(thisLink.fromNode.id) && nodes.includes(thisLink.toNode.id)) {
          thisLink.relations.forEach(item => {
            if (item.styleClass != 'is-opacity') {
              item.lineWidth = 2
              item.styleClass = 'is-not-opacity'
              nodes.push(thisLink.fromNode.id)
              nodes.push(thisLink.toNode.id)
            }
          })
        } else {
          thisLink.relations.forEach(item => {
            item.styleClass = 'is-opacity'
          })
        }
      })
    },

    /**
     * @description: 设置图谱数据
     * @param {*} data
     * @return {*}
     */
    setJsonData(data) {
      this.$refs.relationGraph?.setJsonData(data, () => {
        this.$nextTick(() => {
          this.$refs.relationGraph.zoom(-20)
        })
      })
    },

    /**
     * 查看客户详情
     */
    checkCustomerDetail(id) {
      this.$emit('detail', id)
    },

    /**
     * @description: 获取创建时间
     * @return {*}
     */
    getCreateTime(customerData) {
      return (customerData && customerData.createTime) ? this.$moment(customerData.createTime).format('YYYY-MM-DD') : ''
    },

    /**
     * 筛选
     */
    filterSave(data) {
      if (data.customerName) {
        var _all_nodes = this.$refs.relationGraph.getNodes()
        let node = null
        _all_nodes.forEach(thisNode => {
          if (thisNode.text == data.customerName) {
            node = thisNode
          }
        })
        if (node) {
          this.doFilterByNode(node)
        }
      }
      if (data.hierarchy) {
        if (data.hierarchy == 1) {
          this.doFilterByHierarch()
        }
      }
      if ((data.relation && data.relation !== 'all') || (this.showType > 0)) {
        this.doFilterByRelation(data.relation)
      }

      if (data.hierarchy == 2 && data.relation == 'all' && !data.customerName && this.showType === 0) {
        this.cancelFocus()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.node-item-popover {
  display: flex;
  flex-direction: column;
}

::v-deep .is-opacity {
  opacity: 0.1 !important;
}

::v-deep .is-opacity + g {
  .c-rg-link-text {
    opacity: 0.1 !important;
  }
}

::v-deep .relation-graph {
  .rel-node {
    display: flex;
    align-items: center;
    justify-content: center;

    > span {
      display: flex;
      /* stylelint-disable-next-line value-no-vendor-prefix */
      display: -webkit-box;
      max-height: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
  }
}

::v-deep .is-not-opacity {
  opacity: 1 !important;
}

::v-deep .is-not-opacity + g {
  .c-rg-link-text {
    font-weight: 700;
    opacity: 1 !important;
  }
}
</style>
